import base64
import os
import threading
import time
from urllib import parse

import requests

from comm.chromedriver import ChromeDriverService
from comm.functons import config


class Gua01ImgDecry:
    lock = threading.Lock()

    def __init__(self):
        self.host = config('domain.gua_01')
        self.img_que = []
        self.driver = ChromeDriverService.http_get(self.host, 'Gua01ImgDecry')
        for _ in range(20):
            threading.Thread(target=self._down_img).start()

    def add(self, img):
        self.img_que.insert(0, img)

    def _down_img(self):
        print('_down_img run')
        while True:
            if len(self.img_que) <= 0:
                time.sleep(1)
                continue
            url = self.img_que.pop()
            try:
                ped = parse.urlparse(url)
                dir_path = config('gua_img_dir') + os.path.dirname(ped.path)
                if not os.path.exists(dir_path):
                    with self.lock:
                        os.makedirs(dir_path)

                full_path = config('gua_img_dir') + ped.path
                if not os.path.exists(full_path):
                    self._img_decry(url, full_path)
                    print('下载成功', url)
                else:
                    print('图片已存在', url)
            except Exception as e:
                print('下载失败', e)
                # self.img_que.append(url)

    def _img_decry(self, url, full_path):
        print('_img_decrypt run')
        arr_buf = requests.get(url, headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'}).content
        img_b64 = self.driver.execute_script("return decryptImage(arguments[0])", base64.b64encode(arr_buf).decode('utf-8'))
        with open(full_path, 'wb') as fp:
            fp.write(base64.b64decode(img_b64))


if __name__ == '__main__':
    ...
